import os
import json

from django.core.files.base import ContentFile
from django.core.files.storage import default_storage
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from k3_data_report.config import UPLOAD_TABLE_DIR

# Create your views here.
from django.views.decorators.csrf import csrf_exempt


def home(request):
    file_list = get_file_list(UPLOAD_PATH)
    file_len = len(file_list)
    return render(request, 'index.html', context={"file_list": file_list, "file_len": file_len})

UPLOAD_PATH=UPLOAD_TABLE_DIR

def get_file_list(file_path):
    dir_flist = os.listdir(file_path)
    if not dir_flist:
        return []
    else:
        dir_flist = sorted(dir_flist, key=lambda x: os.path.getmtime(os.path.join(file_path, x)), reverse=True) #按照时间排序
        return dir_flist


def upload_file(request):
    if request.method == "POST":  # 请求方法为POST时，进行处理
        myFile = request.FILES.get("myfile", None)  # 获取上传的文件，如果没有文件，则默认为None
        if not myFile:
            return HttpResponse("no files for upload!")
        #destination = open(os.path.join("E:\\favor_project\\uploads", myFile.name), 'wb+')  # 打开特定的文件进行二进制的写操作
        with open(os.path.join(UPLOAD_PATH, myFile.name), 'wb+') as destination:
            for chunk in myFile.chunks():  # 分块写入文件
                destination.write(chunk)
        file_list = get_file_list(UPLOAD_PATH)
        file_len = len(file_list)
        return render(request, 'index.html', context={"file_list":file_list[:10],"file_len":file_len})
    else:
        file_list = get_file_list(UPLOAD_PATH)
        file_len = len(file_list)
        return render(request,'index.html',  context={"file_list":file_list[:10],"file_len":file_len})


#
# @csrf_exempt
# def file_upload(request):
#     if request.method == 'POST':
#         upload_file = request.FILES.get('file')
#         task = request.POST.get('task_id')  # 获取文件唯一标识符
#         chunk = request.POST.get('chunk', 0)  # 获取该分片在所有分片中的序号
#         filename = '%s%s' % (task, chunk)  # 构成该分片唯一标识符
#         print("filename=", filename)
#         default_storage.save('./upload/%s' % filename, ContentFile(upload_file.read()))  # 保存分片到本地
#     return render_to_response('index.html', locals())
#
#
# @csrf_exempt
# def file_merge(request):
#     print(request.GET)
#     task = request.GET.get('task_id')
#     ext = request.GET.get('filename', '')
#     upload_type = request.GET.get('type')
#     if len(ext) == 0 and upload_type:
#         ext = upload_type.split('/')[1]
#     ext = '' if len(ext) == 0 else '_%s' % ext  # 构建文件后缀名
#     chunk = 0
#     with open('./upload/%s%s' % (task, ext), 'wb') as target_file:  # 创建新文件
#         while True:
#             try:
#                 filename = './upload/%s%d' % (task, chunk)
#                 source_file = open(filename, 'rb')  # 按序打开每个分片
#                 target_file.write(source_file.read())  # 读取分片内容写入新文件
#                 source_file.close()
#             except IOError:
#                 break
#             chunk += 1
#             os.remove(filename)  # 删除该分片，节约空间
#     # 分片重组后文件重命名
#     path = os.path.dirname(os.path.dirname(__file__))
#     old_name = task + ext
#     ext = ext.replace('_', '')
#     new_name = ''
#     print(path + '\\upload\\' + old_name)
#     print(path + '\\upload\\' + new_name)
#     os.rename(path + '\\upload\\' + old_name, path + '\\upload\\' + new_name)
#     return render_to_response('index.html', locals())
